package czk.concrent.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/31 16:56
 */
// 琐超时
public class Test3 {
    private static ReentrantLock lock=new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread t1=new Thread(()->{
            // 线程一，主动去获取锁
            try {
                // 两秒后还没获得锁就不尝试获取锁了
                if (!lock.tryLock(2, TimeUnit.SECONDS)){
                    System.out.println("没有获得锁");
                    // 不继续往下执行
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
            // 获取锁
            try {
                System.out.println("获得了锁");
            }finally {
                // 释放锁
                lock.unlock();
            }
        },"t1");
        // 主线程获取了锁
        lock.lock();
        try {
            System.out.println("主线程获取锁，睡三秒");
            t1.start();
            Thread.sleep(3*1000);
        }finally {
            lock.unlock();
        }
    }
}
